from rest_framework import viewsets
from account.models import Role
from account.serializers import RoleSerializer
from account.filters import RoleFilter
from log.services import log_service
from libs.decorators import permission_required
from libs.enums import Permission, LogModule


class RoleViewSet(viewsets.ModelViewSet):
    queryset = Role.objects.all()
    serializer_class = RoleSerializer
    filterset_class = RoleFilter
    ordering_fields = ('id',)
    log_module = LogModule.ROLE.value

    @permission_required([Permission.ROLE_MANAGE.value])
    def create(self, request, *args, **kwargs):
        return super().create(request, *args, **kwargs)

    def perform_create(self, serializer):
        super().perform_create(serializer)
        log_service.build_create_log(self.request.user, serializer.instance, module=self.log_module,
                                     content=f'创建了角色：{serializer.instance.name}')

    @permission_required([Permission.ROLE_MANAGE.value])
    def partial_update(self, request, *args, **kwargs):
        return super().partial_update(request, *args, **kwargs)

    def perform_update(self, serializer):
        super().perform_update(serializer)
        log_service.build_update_log(self.request.user, serializer.instance, module=self.log_module, content=f'修改了角色：{serializer.instance.name}')

    @permission_required([Permission.ROLE_MANAGE.value])
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        log_service.build_delete_log(request.user, instance, module=self.log_module, content=f'删除了角色：{instance.name}')
        return super().destroy(request, *args, **kwargs)
